package com.leyou.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * cors跨域访问配置-在网关设置CORS过滤器解决，（后台）api网关映射manage前台
 * 跨域-在ajax请求的时候发生--域名不同-二级域名不同，端口不同
 *
 * @author 冯金平
 * @date 2022/08/03
 */
@Configuration
public class LeyouCorsConfig {
    @Bean
    public CorsFilter corsFilter() {//springmvc提供的过滤器
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://manage.leyou.com");//允许跨域的域名后台管理
        configuration.addAllowedOrigin("http://www.leyou.com");//允许跨域的域名前台门户
        configuration.setAllowCredentials(true);//携带COOKIE，上面为*则无法携带
        //最重要的两个参数

        //请求方法
        configuration.addAllowedMethod("OPTIONS");
        configuration.addAllowedMethod("HEAD");
        configuration.addAllowedMethod("GET");
        configuration.addAllowedMethod("PUT");
        configuration.addAllowedMethod("POST");
        configuration.addAllowedMethod("DELETE");
        configuration.addAllowedMethod("PATCH");
        //运许的头信息
        configuration.addAllowedHeader("*");

        //设置路径映射，拦截所有路径的请求，注册cors设置
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", configuration);

        return new CorsFilter(corsConfigurationSource);
    }
}
